package com.agile.leetcode.jvm.fastJsonOutOfMenmory;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.PropertyNamingStrategy;
import com.alibaba.fastjson.serializer.SerializeConfig;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * fastJson内存泄漏的测试 版本1.2.29
 *
 * @Author:ChenZhangKun
 * @Date: 2021/5/26 9:37
 */
public class FastJsonOutOfMemoryTest {
    public static void main(String[] args) throws InterruptedException {

        // 模拟并发
        ThreadPoolExecutor pool = new ThreadPoolExecutor(6, 6, 1, TimeUnit.SECONDS, new ArrayBlockingQueue<>(9999));
        // 死循环
        for (; ; ) {
            TimeUnit.SECONDS.sleep(1);
            // 请求
            pool.submit(FastJsonOutOfMemoryTest::process);
        }
    }

    public static void process() {
        User user = new User("czk", "26", "nan", "成都");
        // 调用
        String s = FastJsonOutOfMemoryTest.outOfMemoryTest(user);

    }

    public static String outOfMemoryTest(User user) {
        try {
            // 创建配置类
            SerializeConfig config = new SerializeConfig();
            config.propertyNamingStrategy = PropertyNamingStrategy.SnakeCase;
            return JSON.toJSONString(user, config);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    static SerializeConfig serializeConfig = new SerializeConfig();

    static {
        serializeConfig.propertyNamingStrategy = PropertyNamingStrategy.SnakeCase;
    }

    /**
     * 解决方案
     *
     * @param user
     * @return
     */
    public static String solutionOutOfMemory(User user) {
        // 将serializeConfig抽象到成员变量和静态代码块，内存中只有一块
        String string = JSON.toJSONString(user, serializeConfig);
        return string;
    }
}

class User {
    public String userName;
    public String userArg;
    public String userGender;
    public String userAddr;

    public User(String userName, String userArg, String userGender, String userAddr) {
        this.userName = userName;
        this.userArg = userArg;
        this.userGender = userGender;
        this.userAddr = userAddr;
    }
}
